package com.example.weight.greenSeasons.compost;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class DuifeiMonthMaintanenceActivity extends AppCompatActivity {

    private String name, role, fName, factory;

    private TextView planDate;

    private CheckBox content1, content2, content3, content4,
            c1Check, c2Check, c3Check, c4Check;

    private EditText c1Text, c2Text, c3Text, c4Text;

    private LinearLayout optionalCheckBox, optionalText;

    private Map<String, String> fromIdMap;

    private RequestQueue queue;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duifei_month_maintanence);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        fName = previousIntent.getStringExtra("fName");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.duifeiMonth_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }
            @Override
            public void onTitleClick(View v) {}
            @Override
            public void onRightClick(View v) {}
        });

        TextView actualDate = findViewById(R.id.duifeiMonth_date);
        String tempText = actualDate.getText().toString();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        actualDate.setText(tempText+year+"年"+month+"月"+day+"日");

        content1 = findViewById(R.id.duifeiMonth_content1);
        content2 = findViewById(R.id.duifeiMonth_content2);
        content3 = findViewById(R.id.duifeiMonth_content3);
        content4 = findViewById(R.id.duifeiMonth_content4);
        c1Check = findViewById(R.id.duifeiMonth_c1_check);
        c2Check = findViewById(R.id.duifeiMonth_c2_check);
        c3Check = findViewById(R.id.duifeiMonth_c3_check);
        c4Check = findViewById(R.id.duifeiMonth_c4_check);
        c1Text = findViewById(R.id.duifeiMonth_c1_text);
        c2Text = findViewById(R.id.duifeiMonth_c2_text);
        c3Text = findViewById(R.id.duifeiMonth_c3_text);
        c4Text = findViewById(R.id.duifeiMonth_c4_text);
        optionalCheckBox = findViewById(R.id.duifeiMonth_optional_checkBox);
        optionalText = findViewById(R.id.duifeiMonth_optional_text);

        fromIdMap = new HashMap<>();

        queue = Volley.newRequestQueue(this);

        // 根据不同系统名称，设置不同保养内容
        switch (fName) {
            case "1#吨袋系统":
            case "2#吨袋系统":
            case "3#吨袋系统":
            case "4#吨袋系统":
                optionalCheckBox.setVisibility(View.GONE);
                optionalText.setVisibility(View.GONE);
                initialCheckStatus(3);
                break;
            case "辅料输送系统":
                content1.setText("测量电机绝缘值");
                content2.setText("检查衬板刷漆");
                content3.setText("检查螺旋叶片及电机减速机除锈刷漆");
                initialCheckStatus(4);
                break;
            case "混料搅拌螺旋":
                content1.setText("检查电源端子");
                content2.setText("检查搅拌耙齿");
                content3.setText("检查螺旋叶片及电机减速机除锈刷漆");
                initialCheckStatus(4);
                break;
            case "混料输送螺旋":
                content1.setText("调整皮带位置");
                content2.setText("更换轴承加注润滑油");
                content3.setText("除锈刷漆");
                content4.setText("更换轴承皮带");
                initialCheckStatus(4);
                break;
            case "泥料输送螺旋":
                content1.setText("检查电源端子");
                content2.setText("除锈刷漆");
                content3.setText("检查螺旋叶片及电机减速机除锈刷漆");
                initialCheckStatus(4);
                break;
            case "堆肥车间曝气系统":
            case "堆肥车间除臭风机":
                content1.setText("检查气密性");
                content2.setText("除锈刷漆");
                content3.setText("轴承加油，叶轮作动平衡");
                content4.setText("更换轴承");
                initialCheckStatus(4);
                break;
        }

        // 操作人填表
        content1.setOnClickListener(v -> {
            if (content1.isChecked()) {
                operatorAddForm(content1, c1Text.getText().toString());
            }
        });
        content2.setOnClickListener(v -> {
            if (content2.isChecked()) {
                operatorAddForm(content2, c2Text.getText().toString());
            }
        });
        content3.setOnClickListener(v -> {
            if (content3.isChecked()){
                operatorAddForm(content3, c3Text.getText().toString());
            }
        });
        content4.setOnClickListener(v -> {
            if (content4.isChecked()) {
                operatorAddForm(content4, c4Text.getText().toString());
            }
        });

        // 检查人填表
        c1Check.setOnClickListener(v -> {
            if (c1Check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(content1.getText().toString())) != null)
                    examinerAddForm(fromId, c1Text.getText().toString(), c1Check);
            }
        });
        c2Check.setOnClickListener(v -> {
            if (c2Check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(content2.getText().toString())) != null)
                    examinerAddForm(fromId, c2Text.getText().toString(), c2Check);
            }
        });
        c3Check.setOnClickListener(v -> {
            if (c3Check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(content3.getText().toString())) != null)
                    examinerAddForm(fromId, c3Text.getText().toString(), c3Check);
            }
        });
        c4Check.setOnClickListener(v -> {
            if (c4Check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(content4.getText().toString())) != null)
                    examinerAddForm(fromId, c4Text.getText().toString(), c4Check);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        Intent intent = new Intent();
        intent.putExtra("needRefresh", true);
        setResult(RESULT_OK, intent);
    }

    private void operatorAddForm(CheckBox checkBox, String comment) {
        String maintainContent = checkBox.getText().toString();
        new AlertDialog.Builder(this)
                .setTitle("确定提交吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
                .setPositiveButton("确定", (dialog, which) -> {
                    checkBox.setEnabled(false);
                    checkBox.setTextColor(Color.GREEN);
                    String url = Config.url + "/shlj/sjqCompostProduceMaintenance/add_month_recorder";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("zys", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(DuifeiMonthMaintanenceActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(DuifeiMonthMaintanenceActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DuifeiMonthMaintanenceActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", fName);
                            map.put("maintenanceContent", maintainContent);
                            map.put("isNormal", comment.equals("")?"1":"0");
                            map.put("remarks", comment);
                            map.put("operator", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }).show();
    }

    private void setCheckStatus(CheckBox operatorCB, CheckBox examinerCB) {
        String maintainContent = operatorCB.getText().toString();
        String url = Config.url + "/shlj/sjqCompostProduceMaintenance/getlast_month";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                operatorCB.setChecked(true);
                                operatorCB.setEnabled(false);
                                operatorCB.setTextColor(Color.GREEN);
                                setRemarks(operatorCB, data.getString("remarks"));

//                                String examiner = data.getString("examiner");
                                if (!data.isNull("inspector") && !data.getString("inspector").equals("") && data.getString("factory").equals(factory) ) {
                                    // 检查人已检查某项，该项不可再检查
                                    examinerCB.setChecked(true);
                                    examinerCB.setEnabled(false);
                                    examinerCB.setTextColor(Color.GREEN);
                                } else {
                                    // 若存在检查人未检查项，将其添加到formIdList中
                                    fromIdMap.put(maintainContent, data.getString("id"));
                                }
//                                if (role.equals("检查人")) {
//
//                                }
                            } else {
                                if (role.equals("检查人")) {
                                    // 如果操作人未保养，检查人不可检查
                                    Log.d("zys", maintainContent);
                                    operatorCB.setEnabled(false);
                                    examinerCB.setEnabled(false);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DuifeiMonthMaintanenceActivity.this,
                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipment_name", fName);
                map.put("maintenanceContent", maintainContent);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    private void examinerAddForm(String formId, String comment, CheckBox checkBox) {
        new AlertDialog.Builder(this)
                .setTitle("确定检查吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
                .setPositiveButton("确定", (dialog, which) -> {
                    checkBox.setEnabled(false);
                    checkBox.setTextColor(Color.GREEN);
                    String url = Config.url + "/shlj/sjqCompostProduceMaintenance/add_month_inspector";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(DuifeiMonthMaintanenceActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(DuifeiMonthMaintanenceActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DuifeiMonthMaintanenceActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", formId);
                            map.put("Inspector", name);
                            map.put("remarks", comment);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }).show();
    }

    private void setRemarks(CheckBox checkBox, String remarks) {
        String content = checkBox.getText().toString();
        switch (fName) {
            case "1#吨袋系统":
            case "2#吨袋系统":
            case "3#吨袋系统":
            case "4#吨袋系统":
                switch (content) {
                    case "测量电流值，检查电源端子":
                        c1Text.setText(remarks);
                        break;
                    case "除锈刷漆":
                        c2Text.setText(remarks);
                        break;
                    case "轴承加注润滑油，变速箱更换齿轮油":
                        c3Text.setText(remarks);
                        break;
                }
                break;
            case "辅料输送系统":
                switch (content) {
                    case "测量电机绝缘值":
                        c1Text.setText(remarks);
                        break;
                    case "检查衬板刷漆":
                        c2Text.setText(remarks);
                        break;
                    case "检查螺旋叶片及电机减速机除锈刷漆":
                        c3Text.setText(remarks);
                        break;
                    case "更换减速机齿轮油":
                        c4Text.setText(remarks);
                        break;
                    default:
                }
                break;
            case "混料搅拌螺旋":
                switch (content) {
                    case "检查电源端子":
                        c1Text.setText(remarks);
                        break;
                    case "检查搅拌耙齿":
                        c2Text.setText(remarks);
                        break;
                    case "检查螺旋叶片及电机减速机除锈刷漆":
                        c3Text.setText(remarks);
                        break;
                    case "更换减速机齿轮油":
                        c4Text.setText(remarks);
                        break;
                    default:
                }
                break;
            case "混料输送螺旋":
                switch (content) {
                    case "调整皮带位置":
                        c1Text.setText(remarks);
                        break;
                    case "更换轴承加注润滑油":
                        c2Text.setText(remarks);
                        break;
                    case "除锈刷漆":
                        c3Text.setText(remarks);
                        break;
                    case "更换轴承皮带":
                        c4Text.setText(remarks);
                        break;
                    default:
                }
                break;
            case "泥料输送螺旋":
                switch (content) {
                    case "检查电源端子":
                        c1Text.setText(remarks);
                        break;
                    case "除锈刷漆":
                        c2Text.setText(remarks);
                        break;
                    case "检查螺旋叶片及电机减速机除锈刷漆":
                        c3Text.setText(remarks);
                        break;
                    case "更换减速机齿轮油":
                        c4Text.setText(remarks);
                        break;
                    default:
                }
                break;
            case "堆肥车间曝气系统":
            case "堆肥车间除臭风机":
                switch (content) {
                    case "检查气密性":
                        c1Text.setText(remarks);
                        break;
                    case "除锈刷漆":
                        c2Text.setText(remarks);
                        break;
                    case "轴承加油，叶轮作动平衡":
                        c3Text.setText(remarks);
                        break;
                    case "更换轴承":
                        c4Text.setText(remarks);
                        break;
                    default:
                }
                break;
        }
    }

    private void initialCheckStatus(int contentNum) {
        setCheckStatus(content1, c1Check);
        setCheckStatus(content2, c2Check);
        setCheckStatus(content3, c3Check);
        if (contentNum == 4)
            setCheckStatus(content4, c4Check);
        if (role.equals("操作人")) {
            c1Check.setEnabled(false);
            c2Check.setEnabled(false);
            c3Check.setEnabled(false);
            if (contentNum == 4)
                c4Check.setEnabled(false);
        }
    }
}